import inquirer from 'inquirer'
import request from 'request'
import fs from 'node:fs'
import path from 'node:path'
const fileName = '.config.json';
const userDir = process.env.USERPROFILE || process.env.HOME;
const filePath = path.join(userDir, fileName);
export const manualCheckIn = async () => {
  if (fs.existsSync(filePath)) {
    const optionsConfig = [
      {
        type: "confirm",
        message: "是否重新配置文件",
        name: "genderConfirm",
        suffix: "必答题",
      }
    ];
    inquirer.prompt(optionsConfig).then(async (res) => {
      if (res.genderConfirm) {
        const options = [
          {
            type: 'input',
            name: 'getCookie',
            message: '请输入你的cookie',
          },
          {
            type: 'input',
            name: 'getAid',
            message: '请输入你的aid',
          },
          {
            type: 'input',
            name: 'getUid',
            message: '请输入你的uid',
          },
        ];
        const answers = await inquirer.prompt(options)
        const cookie = `sessionid=${answers.getCookie}`
        const url = 'https://juejin.cn/'
        const check_url = `https://api.juejin.cn/growth_api/v1/check_in?aid=${answers.getAid}&uid=${answers.getUid}`
        const configData = {
          cookie,
          url,
          check_url
        };
        const configString = `${JSON.stringify(configData, null, 2)}`;
        fs.writeFile(filePath, configString, 'utf8', (err) => {
          if (err) {
            console.error('写入文件时发生错误:', err);
            return;
          }
        });
        signInApi(configData)
      } else {
        readFile(filePath)
      }
    })
    return
  }
  configuration()
}


const signInApi = ({ check_url, url, cookie }) => {
  request(check_url, {
    method: 'post',
    headers: {
      Referer: url,
      Cookie: cookie
    },
  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body)
    }
  })
}
const configuration = async () => {
  const options = [
    {
      type: 'input',
      name: 'getCookie',
      message: '请输入你的cookie',
    },
    {
      type: 'input',
      name: 'getAid',
      message: '请输入你的aid',
    },
    {
      type: 'input',
      name: 'getUid',
      message: '请输入你的uid',
    },
  ];
  const answers = await inquirer.prompt(options)
  const cookie = `sessionid=${answers.getCookie}`
  const url = 'https://juejin.cn/'
  const check_url = `https://api.juejin.cn/growth_api/v1/check_in?aid=${answers.getAid}&uid=${answers.getUid}`
  const configData = {
    cookie,
    url,
    check_url
  };
  const configString = `${JSON.stringify(configData, null, 2)}`;
  fs.writeFile(filePath, configString, 'utf8', (err) => {
    if (err) {
      console.error('写入文件时发生错误:', err);
      return;
    }
  });
  return configData
}
const del = (filePath) => {
  try {
    fs.unlinkSync(filePath);
    console.log(`${filePath} 删除成功`);
  } catch (err) {
    console.error(`删除失败 ${err}`);
  }
}

const readFile = (filePath) => {
  try {
    fs.readFile(filePath, 'utf8', function (err, data) {
      if (err) {
        console.error(`读取文件时出错: ${err}`);
      } else {
        const jsonData = JSON.parse(data);
        console.log('读取到本地配置，开始签到')
        signInApi(jsonData)
      }
    })
  } catch (err) {
    console.error(`读取文件时出错 ${err}`);
  }
}